package com.xkdx.caipiao;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.loopj.android.image.SmartImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xkdx.caipiao.hall.ArrangeFiveActivity;
import com.xkdx.caipiao.hall.ArrangeThreeActivity;
import com.xkdx.caipiao.hall.BetFiveActivity;
import com.xkdx.caipiao.hall.BetLottoActivity;
import com.xkdx.caipiao.hall.BetSevenActivity;
import com.xkdx.caipiao.hall.BetThreeActivity;
import com.xkdx.caipiao.hall.LottoActivity;
import com.xkdx.caipiao.hall.SevenActivity;
import com.xkdx.caipiao.module.network.AbsModule;
import com.xkdx.caipiao.presistence.navigation.NavigationAction;
import com.xkdx.caipiao.presistence.navigation.NavigationInfo;
import com.xkdx.caipiao.presistence.navigation.NavigationModule;
import com.xkdx.caipiao.presistence.navigation.NavigationPresistence;
import com.xkdx.caipiao.presistence.quert.TypeQueryAction;
import com.xkdx.caipiao.presistence.quert.TypeQueryItemInfo;
import com.xkdx.caipiao.presistence.quert.TypeQueryModule;
import com.xkdx.caipiao.presistence.quert.TypeQueryPresistence;
import com.xkdx.caipiao.presistence.versioninfo.VersionInfoAction;
import com.xkdx.caipiao.presistence.versioninfo.VersionInfoInfo;
import com.xkdx.caipiao.presistence.versioninfo.VersionInfoModule;
import com.xkdx.caipiao.presistence.versioninfo.VersionInfoPresistence;
import com.xkdx.caipiao.pubclass.FirstTitleQueryItem;
import com.xkdx.caipiao.statics.IConstants;
import com.xkdx.caipiao.wiget.AutoTextView;
import com.xkdx.caipiao.wiget.MyToast;
import com.xkdx.caipiao.wiget.XListView;
import com.xkdx.caipiao.wiget.XListView.IXListViewListener;
import com.xkdx.guangguang.util.SharePrefenceUtil;

public class LotteryHallActivity extends ThreadActivity implements
		IXListViewListener {
	public static String lotteryid = "";
	public static String tga = "TGA";
	XListView mListViewLotteryHall;
	List<TypeQueryItemInfo> hallList;
	List<NavigationInfo> List1;
	List<FirstTitleQueryItem> firtList;
	Drawable[] logos;
	String[] names;
	TypeQueryAction action;
	TypeQueryModule module;
	TypeQueryPresistence presistence;

	NavigationAction action1;
	NavigationModule module1;
	NavigationPresistence presistence1;
	ImageLoader imageLoader = ImageLoader.getInstance();
	DisplayImageOptions options;
	ViewFlipper viewFlipper;
	String devicetype;

	VersionState isHaveCheckedVertion;// NEVERCHECK:没请求国-》PREPAIRCHECK准备请求-》FINISHCHECK再不请求
	private VersionInfoModule modulev;
	private VersionInfoAction actionv;
	private VersionInfoPresistence presistencev;

	enum VersionState {
		NEVERCHECK, PREPAIRCHECK, FINISHCHECK
	};

	long daySta, hourSta, minSta, secondSta;
	private AutoTextView tv_3d;
	/**
	 * 滚动消息
	 */
	int i = -1;
	Timer timerTitle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		isHaveCheckedVertion = VersionState.NEVERCHECK;
		setContentView(R.layout.activity_lottery_hall_caipiao);
		options = new DisplayImageOptions.Builder().bitmapConfig(
				Bitmap.Config.RGB_565).build();

		init();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	private void init() {
		
		mListViewLotteryHall = (XListView) findViewById(R.id.lv_lottery_hall);
		mListViewLotteryHall.setFooterViewInVisible();
		mListViewLotteryHall.setPullRefreshEnable(true);
		mListViewLotteryHall.setXListViewListener(this);
		hallList = new ArrayList<TypeQueryItemInfo>();
		tv_3d = (AutoTextView) findViewById(R.id.tv_3d);

		viewFlipper = (ViewFlipper) findViewById(R.id.shop_focuse_im);
		viewFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.slide_right_in));
		viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.slide_left_out));
		//initViewFlipper();
		mListViewLotteryHall.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				lotteryid = hallList.get(position - 1).getLotteryid();
				if (lotteryid.equals("dlt")) {
					int count = IConstants.list_selectcode.size();
					if (count > 0) {
						Intent intent = new Intent(LotteryHallActivity.this,
								BetLottoActivity.class);
						startActivity(intent);
						try {
							Thread.sleep(100);

							MyToast.makeText(LotteryHallActivity.this,
									"这是您上次保存的号码", 0).show();
						} catch (InterruptedException e) {

							e.printStackTrace();
						}
					} else {
						Intent intent = new Intent(LotteryHallActivity.this,
								LottoActivity.class);
						startActivity(intent);
					}
				}

				else if (lotteryid.equals("qxc")) {
					int count = IConstants.list_sevencolor.size();
					if (count > 0) {
						Intent intent1 = new Intent(LotteryHallActivity.this,
								BetSevenActivity.class);
						startActivity(intent1);
						try {
							Thread.sleep(100);
							MyToast.makeText(LotteryHallActivity.this,
									"这是您上次保存的号码", 0).show();
						} catch (InterruptedException e) {

							e.printStackTrace();
						}
					} else {

						Intent intent1 = new Intent(LotteryHallActivity.this,
								SevenActivity.class);
						startActivity(intent1);
					}
				} else if (lotteryid.equals("pls")) {
					int count = IConstants.list_three.size();
					if (count > 0) {
						Intent intent2 = new Intent(LotteryHallActivity.this,
								BetThreeActivity.class);
						startActivity(intent2);
						try {
							Thread.sleep(100);
							MyToast.makeText(LotteryHallActivity.this,
									"这是您上次保存的号码", 0).show();
						} catch (InterruptedException e) {

							e.printStackTrace();
						}

					} else {
						Intent intent2 = new Intent(LotteryHallActivity.this,
								ArrangeThreeActivity.class);
						startActivity(intent2);
					}
				} else {
					int count = IConstants.list_five.size();
					if (count > 0) {
						Intent intent3 = new Intent(LotteryHallActivity.this,
								BetFiveActivity.class);
						startActivity(intent3);
						try {
							Thread.sleep(100);
							MyToast.makeText(LotteryHallActivity.this,
									"这是您上次保存的号码", 0).show();
						} catch (InterruptedException e) {

							e.printStackTrace();
						}
					} else {
						Intent intent3 = new Intent(LotteryHallActivity.this,
								ArrangeFiveActivity.class);
						startActivity(intent3);
					}
				}
			}

		});

	}


	// 添加视图
	private View getImageView(int resId) {
		View view = LayoutInflater.from(getApplicationContext()).inflate(resId,
				null);
		return view;
	}

	public class HallAdapter extends BaseAdapter {
		Context context;

		public HallAdapter(Context context) {
			this.context = context;
		}

		@Override
		public int getCount() {
			return hallList.size();
		}

		@Override
		public Object getItem(int position) {
			return hallList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(
						R.layout.lottery_hall_lv_item_caipiao, null);
				viewHolder.logo = (ImageView) convertView
						.findViewById(R.id.logo);
				viewHolder.name = (TextView) convertView
						.findViewById(R.id.lottery_name);

				viewHolder.openawardtime = (TextView) convertView
						.findViewById(R.id.period_info);
				viewHolder.pool = (TextView) convertView
						.findViewById(R.id.pool_info);
				viewHolder.tip = (ImageView) convertView
						.findViewById(R.id.icon_lottery_tip);

				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}

 
			String name = hallList.get(position).getLotteryid();

			if (name.equals("qxc")) {
				viewHolder.name.setText("七星彩");
				viewHolder.logo.setImageResource(R.drawable.logo_seven_color_caipiao);
				viewHolder.pool.setText(hallList.get(position).getDesc());
			} else if (name.equals("dlt")) {
				viewHolder.name.setText("大乐透");
				viewHolder.logo.setImageResource(R.drawable.logo_lotto_caipiao);
				viewHolder.pool.setText(hallList.get(position).getDesc());
			} else if (name.equals("pls")) {
				viewHolder.name.setText("排列三");
				viewHolder.logo.setImageResource(R.drawable.logo_arrange_3_caipiao);
				viewHolder.pool.setText(hallList.get(position).getDesc());
			} else if(name.equals("plw")){
				viewHolder.name.setText("排列五");
				viewHolder.logo.setImageResource(R.drawable.logo_arrange_5_caipiao);
				viewHolder.pool.setText(hallList.get(position).getDesc());
			} else if(name.equals("ssq")){
				viewHolder.name.setText("双色球");
				viewHolder.logo.setImageResource(R.drawable.logo_ssq_caipiao);
				viewHolder.pool.setText(hallList.get(position).getDesc());
			} else if(name.equals("3d")){
				viewHolder.name.setText("福彩3D");
				viewHolder.logo.setImageResource(R.drawable.logo_fucai_caipiao);
				viewHolder.pool.setText(hallList.get(position).getDesc());
			}

			String time = dateDiff(IConstants.getCurrentTime(),
					hallList.get(position).getOpenawardtime(),
					"yyyy-MM-dd hh:mm:ss");

			viewHolder.openawardtime.setText(hallList.get(position)
					.getIssueid() + "期截止:" + time);

			if (daySta > 0 || hourSta < 0) {
				viewHolder.tip.setVisibility(View.GONE);
			} else {

				viewHolder.tip.setVisibility(View.VISIBLE);
			}

			return convertView;
		}

		class ViewHolder {

			ImageView logo, tip;
			TextView name, openawardtime, pool;

		}

	}

	@Override
	public void showOnPost(HashMap<String, AbsModule> result) {
		dataLoadDialog.dismiss();
		if (advertise) {
			advertise = false;
			if (result.containsKey("0")) {
				for (int i = 0; i < module1.list.size(); i++) {
					thumb = module1.list.get(i).getThumb();
					View view =View.inflate(LotteryHallActivity.this, R.layout.viewpager1_caipiao, null);
					SmartImageView sivIcon = (SmartImageView) view.findViewById(R.id.siv_icon);
					sivIcon.setImageUrl(thumb);
					viewFlipper.addView(sivIcon);
					
				}
				Timer timer = new Timer();
				timer.schedule(new TimerTask() {
					@Override
					public void run() {
						nextHandler.sendEmptyMessage(1);
					}
				}, 0, 3000);
			}
		}

		if (VersionState.PREPAIRCHECK == isHaveCheckedVertion) {
			// 检查版本版本
			isHaveCheckedVertion = VersionState.FINISHCHECK;
			if (result.containsKey("0")) {
				ArrayList<VersionInfoInfo> list = modulev.list;
				if (modulev.list.size() > 0) {
					final String urlStr = modulev.list.get(0).getUrl();
					if (urlStr.length() > 0) {
						AlertDialog.Builder builder = new AlertDialog.Builder(
								this);
						builder.setTitle("有新版本,是否更新");
						builder.setNegativeButton("是",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										download(urlStr);
									}
								});
						builder.setPositiveButton("否", null);
						builder.create().show();
					}
				}
			}
			startThread1();
			return;
		}

		if (result.containsKey("0")) {

			setFirstTitle();
			SharePrefenceUtil su = new SharePrefenceUtil(this,
					SharePrefenceUtil.LOTTERYTYPE);
			su.saveObject(SharePrefenceUtil.LOTTERYTYPE, module.typeQueryInfo);
			hallList = module.typeQueryInfo.getList();
		}

		HallAdapter adapter = new HallAdapter(this);
		mListViewLotteryHall.setAdapter(adapter);
		onLoad();
		if (isHaveCheckedVertion == VersionState.NEVERCHECK) {
			startVThread();
			isHaveCheckedVertion = VersionState.PREPAIRCHECK;
		}

	}
	private void setFirstTitle() {
		firtList = module.firstTitleQueryInfo.getList();
		if (0 == firtList.size()) {
			return;
		}
		timerTitle = new Timer();
		timerTitle.schedule(new TimerTask() {
			@Override
			public void run() {

				nextHandler.sendEmptyMessage(2);
				if (i == firtList.size() - 1) {
					i = 0;
				} else {
					i++;
				}
			}
		}, 0, 4000);

	}


	@Override
	public void startThread() {
		if (!(dataLoadDialog.isShowing())) {
			dataLoadDialog.show();
			dataLoadDialog.setContentView(R.layout.progressbar_caipiao);
		}
		action = new TypeQueryAction();
		module = new TypeQueryModule();
		presistence = new TypeQueryPresistence(this);
		presistence.setActitons(action);
		presistence.setModule(module);
		presistence.execute();
	}

	public void startThread1() {
		if (!(dataLoadDialog.isShowing())) {
			dataLoadDialog.show();
			dataLoadDialog.setContentView(R.layout.progressbar_caipiao);
		}
		advertise = true;
		action1 = new NavigationAction(devicetype);
		module1 = new NavigationModule();
		presistence1 = new NavigationPresistence(this);
		presistence1.setActitons(action1);
		presistence1.setModule(module1);
		presistence1.execute();
	}

	public String dateDiff(String startTime, String endTime, String format) {
		// 按照传入的格式生成一个simpledateformate对象
		SimpleDateFormat sd = new SimpleDateFormat(format);
		long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
		long nh = 1000 * 60 * 60;// 一小时的毫秒数
		long nm = 1000 * 60;// 一分钟的毫秒数
		long ns = 1000;// 一秒钟的毫秒数
		long diff;
		try {
			// 获得两个时间的毫秒时间差异
			diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
			long day = diff / nd;// 计算差多少天
			long hour = diff % nd / nh;// 计算差多少小时
			long min = diff % nd % nh / nm;// 计算差多少分钟
			long sec = diff % nd % nh % nm / ns;// 计算差多少秒

			daySta = day;
			hourSta = hour;
			minSta = min;
			secondSta = sec;
			// 输出结果
			if (day == 0) {
				return hour + "小时" + min + "分钟";
			} else {
				return day + "天" + hour + "小时" + min + "分钟";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	@Override
	public void onRefresh() {
		startThread();
	}

	@Override
	public void onLoadMore() {

	}

	private void onLoad() {
		mListViewLotteryHall.stopRefresh();
		mListViewLotteryHall.stopLoadMore();
		mListViewLotteryHall.setRefreshTime(getCurrentTime());
	}

	private String getCurrentTime() {
		SimpleDateFormat format = new SimpleDateFormat("MM月dd日 hh:mm:ss");
		Date date = new Date(System.currentTimeMillis());
		return format.format(date);
	}

	protected void onResume() {
		super.onResume();
		if (timerTitle != null) {
			timerTitle.cancel();
			timerTitle = null;
		}

		startThread();

	};

	Handler nextHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				viewFlipper.showNext();
				break;
			case 2:
				String title = firtList.get(i).getTitle();
				tv_3d.setText(title);
				break;
			default:
				break;
			}

		}
	};
	private boolean advertise;
	private String thumb;

	/*
	 * 发起版本更新检查
	 */
	public void startVThread() {
		actionv = new VersionInfoAction("", "");
		modulev = new VersionInfoModule();
		presistencev = new VersionInfoPresistence(this);
		presistencev.setActitons(actionv);
		presistencev.setModule(modulev);
		presistencev.execute();

	}

	/*
	 * 从后台更新
	 */
	private void download(String clientDownloadUrl) {
		IConstants.download(this, clientDownloadUrl);
	}

	@Override
	public void onBackClick(View view) {
		finish();
	}
	
	 
}
